package com.group01.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.group01.utils.properties.AliOSSProperties;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * &#064;Classname  AliOssUtil
 * @Description TODO
 * @Date 2024/3/15 11:45
 * &#064;Created  by zyl
 * &#064;Version  v1.0.0
 */
@Data
@Slf4j
@ConfigurationProperties(prefix = "ali")
@Component
public class AliOSSUtils {

    /**
     * 注入阿里云OSS的配置信息
     */
    private AliOSSProperties aliOSSProperties;

    public AliOSSUtils(AliOSSProperties aliOSSProperties) {
        this.aliOSSProperties = aliOSSProperties;
    }

    /**
     * 以下是一个实现上传文件到OSS的方法，并不唯一
     */

    public String upload(MultipartFile file) throws IOException {
        //获取阿里云OSS参数
        String endpoint = aliOSSProperties.getEndpoint();
        String accessKeyId = aliOSSProperties.getAccessKeyId();
        String accessKeySecret = aliOSSProperties.getAccessKeySecret();
        String bucketName = aliOSSProperties.getBucketName();

        // 获取上传的文件的输入流
        InputStream inputStream = file.getInputStream();

        // 避免文件覆盖，需要使用UUID将文件重命名
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名为空");
        }
        int dotIndex = originalFilename.lastIndexOf(".");
        if (dotIndex == -1) {
            throw new IllegalArgumentException("文件名不包含扩展名");
        }
        String fileName = UUID.randomUUID() + originalFilename.substring(dotIndex);

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);

        // 文件访问路径，可自行更改逻辑，重点是拼接url
        String[] endpointParts = endpoint.split("\\.");
        if (endpointParts.length != 3) {
            throw new IllegalArgumentException("无效的 endpoint 格式");
        }
        //url拼接
        String url = "https://" + bucketName + "." + endpointParts[0] + "." + endpointParts[1] +  "." + endpointParts[2] + "/" + fileName;

        // 关闭ossClient
        ossClient.shutdown();

        // 把上传到oss的路径返回
        return url;
    }
}
